package blazingbubble.network.game.strategy;

import moltencore.network.protocol.GameStartingNotification;
import spark.network.protocol.Response;
import spark.network.strategy.IProtocolHandleStrategy;
import spark.network.protocol.Base;
import spark.network.protocol.Acknowledgement;
import org.apache.log4j.Logger;
import blazingbubble.game.Game;
import blazingbubble.game.command.net.NetGameCommandFactory;
import spark.utility.OutWrapper;

import java.util.Collection;
import java.util.LinkedList;

public class GameStartingNotificationStrategy implements IProtocolHandleStrategy<GameStartingNotification> {
	private Logger logger = Logger.getLogger(GameStartingNotificationStrategy.class);

	private Game game;
	private NetGameCommandFactory netGameCommandFactory;

	public GameStartingNotificationStrategy(Game game, NetGameCommandFactory netGameCommandFactory) {
		this.game = game;
		this.netGameCommandFactory = netGameCommandFactory;
	}

	@Override
	public void handle(GameStartingNotification packet, OutWrapper<Response> acknowledgement, Collection<Base> additionalData) {
		game.setTeamSize(packet.getTeamSize());
		LinkedList<Long[]> playerFieldPairs = packet.getPlayerFieldPairs();
		for(Long[] playerFieldPair : playerFieldPairs) {
			game.pairPlayerAndField(
					playerFieldPair[GameStartingNotification.PLAYER_FIELD_PAIR_PLAYER_ID_INDEX],
					playerFieldPair[GameStartingNotification.PLAYER_FIELD_PAIR_FIELD_ID_INDEX]);
		}
		if(game.getState() == Game.State.AllPlayersPairedWithFields) {
			netGameCommandFactory.getReadyToPlay().readyToPlay();
		}
		acknowledgement.value = new Acknowledgement(packet);
	}
}